import { LinRouter, ParametersException, Forbidden } from 'lin-mizar';
import { TencentUploader } from '../../extension/file/tencent-uploader';
import { loginRequired } from '../../middleware/jwt';
import { LocalUploader } from '../../extension/file/local-uploader';

const file = new LinRouter({
  prefix: '/cms/file'
});

file.linPost('upload', '/', loginRequired, async ctx => {
  const files = await ctx.multipart();
  if (files.length < 1) {
    throw new ParametersException({ code: 10033 });
  }
  const uploader = new LocalUploader();
  const arr = await uploader.upload(files);
  ctx.json(arr);
});

file.linPost('tencentUpload', '/tencentUpload', async ctx => {
  const files = await ctx.multipart();
  if (files.length < 1) {
    throw new ParametersException({ code: 10033 });
  }
  try {
    const uploader = new TencentUploader();
    const arr = await uploader.upload(files);
    ctx.json(arr);
  } catch (error) {
    throw new Forbidden({
      message: `cos 上传失败: ${error.toString()}`
    });
  }
});

file.linPost('audioUpload', '/audioUpload', async ctx => {
  const files = await ctx.multipart();
  if (files.length < 1) {
    throw new ParametersException({ code: 10033 });
  }
  try {
    const uploader = new TencentUploader('audio-1325476796');
    const arr = await uploader.upload(files);
    ctx.json(arr);
  } catch (error) {
    console.log(error);
    throw new Forbidden({
      message: `cos 上传失败: ${error.toString()}`
    });
  }
});

export { file };
